﻿using LPLS.Commons.DBModule;
using LPLS.Commons.Enums;
using LPLS.DBEntities;
using LPLS.DBEntities.ConfigModels.AlarmModels.AlarmVarableCodeRuleConfigModels;
using LPLS.DBEntities.OEEModule.OEEModels.DataStatisticModels;
using LPLS.DBInterface.ConfigModels.DeviceInfoModels;
using LPLS.DBInterface.OEEModule.OEEModels.DataStaticsticModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LPLS.DBServices.DataCollectionModels
{
    public class CompentDataStatisticsService : DBBaseService, ICompentDataStatisticsService
    {

        private readonly IDeviceBaseInfoService _deviceBaseInfoService;
        public CompentDataStatisticsService(DBContext dbContext, IDeviceBaseInfoService deviceBaseInfoService) : base(dbContext)
        {
            _deviceBaseInfoService= deviceBaseInfoService;
        }

        public int AddData(List<CompentDataStatistics> li)
        {

           
           return this.Client.Insertable<CompentDataStatistics>(li).ExecuteCommand();
        }

        public List<CompentDataStatistics> GetData(DateTime startTime, DateTime endTime, Guid deviceid)
        {
          var deviceli=  _deviceBaseInfoService.GetData().Where(e => e.ID == deviceid).ToList();

            if (deviceli.Count==0)
            {
                return new List<CompentDataStatistics>();
            }

            var deviceinfo=deviceli.FirstOrDefault();
            var compents = deviceinfo.DeviceComponents;
            var  compentlist= this.Client.Queryable<CompentDataStatistics>().Where(e=>e.StartTime>=startTime&&e.EndTime<=endTime&&e.DeviceID==deviceid).ToList();

            Parallel.For(0, compentlist.Count, (i) => 
            { 
            
            var compentinfo= compents.Where(e=>e.ID== compentlist[i].CompentId)?.FirstOrDefault();

                if (compentinfo != null) 
                {
                    compentlist[i].DeviceName = deviceinfo.DeviceName;
                    compentlist[i].CompentStatusDesc=StatusEnumHelper.GetDescription(compentlist[i].Status);
                    compentlist[i].ComponentName=compentinfo.ComponentName;
                    compentlist[i].CompentTypeEnum = compentinfo.ComponentType;
                    compentlist[i].CompentTypeName= DeviceComponentEnumExtension.GetDescription(compentinfo.ComponentType);

                }
            
            
            });


            return compentlist;



        }

        public List<CompentDataStatistics> GetData(DateTime startTime, DateTime endTime, Guid deviceid, string tubeComponentCode)
        {
            throw new NotImplementedException();
        }

        public override void InitDataBaseName()
        {
            DataBaseName = DatabaseEnum.CollectionDataResult.ToString();
        }
    }
}
